<template>
  <div ref="container" class="lazy-rich-wrapper">
    <!-- 占位显示 -->
    <div v-if="!loaded" class="placeholder">
      富文本加载中...
    </div>

    <!-- 富文本组件 -->
    <component v-else :is="RichTextEditor" v-model="localValue" />
  </div>
</template>

<script setup>
import { ref, defineAsyncComponent, onMounted, watch, nextTick } from 'vue'

// 异步加载真实富文本组件
const RichTextEditor = defineAsyncComponent(() => import('./RichTextEditor.vue'))

// 接收父组件 v-model
const props = defineProps({ modelValue: String })
const emit = defineEmits(['update:modelValue'])

// 是否加载真实富文本组件
const loaded = ref(false)
const container = ref(null)

// 中间值，解决直接修改 prop 报错
const localValue = ref(props.modelValue)

// 父组件更新时同步到 localValue
watch(() => props.modelValue, val => {
  localValue.value = val
})

// localValue 改变时通知父组件
watch(localValue, val => emit('update:modelValue', val))

// IntersectionObserver 单例
let observer = null

function loadEditor() {
  loaded.value = true
}

// 初始化 IntersectionObserver
function initObserver() {
  if (!container.value) return

  if (!observer) {
    observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const comp = entry.target._lazyRich
          comp.loadEditor()
          observer.unobserve(entry.target)
        }
      })
    }, { rootMargin: '100px' })
  }

  container.value._lazyRich = { loadEditor }
  observer.observe(container.value)
}

onMounted(async () => {
  await nextTick()
  initObserver()
})
</script>

<style scoped>
.lazy-rich-wrapper {
  min-height: 200px;
  margin-bottom: 12px;
}
.placeholder {
  min-height: 200px;
  border: 1px dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}
</style>
